<template>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >

      <!-- <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item> -->
    </el-form>
   <!-- 列表 -->
   <ContentWrap>
    <el-table v-loading="loading" :data="list" row-key="id" :stripe="true" :show-overflow-tooltip="true" ref="tableRef"  @selection-change="handleSelectionChange">
      <el-table-column width="30" label="选择" type="selection" />
      <el-table-column prop="name" align="center" label="科室名称" />
      <el-table-column prop="count" label="带量数量" width="180">
        <template v-slot="scope">
          <el-input 
            v-model="scope.row.count" 
            :placeholder="isRowSelected(scope.row) ? '请输入带量数量' : '0'" 
            :disabled="!isRowSelected(scope.row)"
            @input="validateCountSum(scope.row)" 
          />
        </template>
      </el-table-column>
    </el-table>
   <!-- 分页 -->
   <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    </ContentWrap>
</template>
<script setup lang="ts">
import { DepartQuantityApi } from '@/api/spd/manager/departquantity'
import {DeptVO} from '@/api/system/dept'
import { ref, reactive, watch, computed } from 'vue';

const loading = ref(true) // 列表的加载中
const list = ref<DeptVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const tableRef = ref<InstanceType<typeof ElTable>>(); // 表格引用

// 从父组件接收带量总数
const props = defineProps<{
  id: number // 部门id（主表的关联字段）
  quantityCount: number // 带量总数
}>()

const formRef = ref() // 表单 Ref
const queryFormRef = ref() // 搜索的表单
const queryParams = reactive({
  pageNo: 1,
  id:0,
  pageSize: 100,
  name: undefined,
  status: undefined
})

// 选中的行
const selectionList = ref<DeptVO[]>([])

// 检查行是否被选中
const isRowSelected = (row: DeptVO) => {
  return selectionList.value.some(item => item.id === row.id)
}

watch(() => props.id, async (newId) => {
  if (newId !== undefined) {
    queryParams.id = newId;
    await getList();
  }
}, { immediate: true }); 

/** 查询部门列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.id = props.id
    const data = await DepartQuantityApi.getDeptPage(queryParams)
    list.value = data
    console.log("`````",list.value)
    
  } finally {
    loading.value = false
  }
    getPreSelectedProductIds(props.id);
  
}

const getPreSelectedProductIds = async (productId: number): Promise<number[]> => {
 
  try {
    // 假设 ProductApi.getProductIdsBySupplier 是一个返回产品 ID 列表的 API
    const productIds = await DepartQuantityApi.getQuantity(productId);
   
    if (tableRef.value && list.value.length > 0) {
      if(productIds.length<=0){
        list.value.forEach(count =>{
          count.count = ""
        });
      }
      // 清空当前的选中项
      tableRef.value.clearSelection();
      // 根据返回的 productIds 设置选中项
      productIds.forEach(productId => {
        const row = list.value.find(row => row.id === productId.deptId);
        if (row) {
          tableRef.value.toggleRowSelection(row, true);
        }
      });
    }
    return productIds;
  } catch (error) {
    return []; // 在发生错误时返回一个空数组，或者您可以根据需求抛出错误
  }
};

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return selectionList.value
}

/** 选中操作 */
const handleSelectionChange = (rows: DeptVO[]) => {
  selectionList.value = rows
}

/** 验证带量数量总和 */
const validateCountSum = (row: DeptVO) => {
  // 只验证选中的行
  if (!isRowSelected(row)) return;
  
  // 获取当前输入的值
  const currentValue = row.count ? parseInt(row.count) : 0;
  
  // 计算所有选中行的总和
  const selectedSum = selectionList.value.reduce((acc, item) => {
    // 排除当前行
    if (item.id === row.id) return acc;
    
    const count = item.count ? parseInt(item.count) : 0;
    return acc + count;
  }, 0);
  
  // 计算新的总和
  const newSum = selectedSum + currentValue;
  
  // 获取带量总数（从props获取）
  const quantityCount = props.quantityCount || 0;
  
  // 如果新的总和超过限制，阻止输入并恢复到之前的值
  if (newSum > quantityCount) {
    alert(`带量数量总和不能超过带量总数 ${quantityCount}！`);
    // 恢复为之前的值
    row.count = (parseInt(row.count) - (newSum - quantityCount)).toString();
  }
}

defineExpose({ validate, getData })
</script>